var express = require('express');
var router = express.Router();
let {randomCode,sendCode}=require('./code1')
let {rigisterModel,tokenModel} =require('../model/model')
 var multiparty = require('multiparty');
 var { setAccessToken,     // 定义短Token
  setRefreshToken,    // 定义长Token
  testAccessToken,    // 验证短token是否过期
  testRefreshToken  // 验证长token是否过期
} = require('../token/index');
 
//图片上传
router.post('/upload', async (req, res) => {
  let form = new multiparty.Form();//创建表单对象
  form.uploadDir = 'upload';//设置上传目录
  form.parse(req , async (err, fields, files) => {  //解析请求体：
    if (err) {//错误处理
      return res.status(500).send({ code: 500, msg: '上传失败', error: err.message });
    }
    
    let filePath = files.file[0].path;//获取文件路径
    //计算文件相对于根目录的路径，即去掉绝对路径前缀的部分。
    let relativePath = `http://localhost:3000/${filePath}`;
    res.send({//成功响应
      code: 200,
      path: relativePath
    });
  });
});
//获取验证码接口
router.get("/code", async (req, res) => {
  let code = randomCode(4);//生成6位数字随机验证码
  sendCode(req.query.phone, code, function (success) {
    if (success) {
      res.send({
        code: 200,
        msg: "短信验证码发送成功",
        codes: code
      });
    } else {
      res.send("短信验证码发送失败");
    }
  })
})
//注册接口
router.post("/reg", async (req, res) => {
  let data=await rigisterModel.findOne({phone:req.body.phone})
  if(data){
      res.send({
          code:201,
          msg:"该手机号已被注册"
      })
  }else{
    await rigisterModel.create(req.body)
    res.send({
        code: 200,
        msg: "注册成功"
    })
  }
    
})
//登录接口
router.post("/login", async (req, res) => {
  let {phone,password}=req.query
  let data=await rigisterModel.findOne({phone:phone})
  console.log(data);
   if(data){
    if(data.password===password){
      console.log(data.password);
     let token = await tokenModel.find().lean()//获取token列表
     if (token.length !== 0) {//删除第一个token
      let id = token[0]._id
      await tokenModel.deleteOne({ _id: id })
    }
    let accesstoken = setAccessToken()//获取短token
    let refreshtoken = setRefreshToken()//获取长token
    await tokenModel.create({ token: refreshtoken })//把长token存入数据库
    console.log('登录');
       res.send({
          code:200,
          msg:"登录成功",
          data,
          accesstoken,
      })
    }else{
      res.send({
          code:202,
          msg:"密码错误"
      })
    }
   }else{
    //不存在
    console.log('登录失败');
       res.send({
          code:201,
          msg:"该手机号未注册"
       })
   }
})
 
router.post('/mess',async(req,res)=>{
  let {phone}=req.query
  let data=await rigisterModel.findOne({phone:phone})
  res.send({
    code:200,
    msg:"查询成功",
    data:data
  })
})

const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
const IaiClient = tencentcloud.iai.v20200303.Client;

// 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
const clientConfig = {
  credential: {
    secretId: "AKID2weAcrsmV2Na1dGsY5VlpfJC32iHvSuO",
    secretKey: "OqIfwAOWk4Uo2ADAFKCqMkyylKgGj282",
  },
  Version:'2020-03-03',
  Action:'SearchPersonsReturnsByGroup',
  region: "ap-beijing",
  profile: {
    httpProfile: {
      endpoint: "iai.tencentcloudapi.com",
    },
  },
};

router.post('/authface',(req,res)=>{
  let imgbase=req.body.imageBase64;
  
  
  
  // 实例化要请求产品的client对象,clientProfile是可选的
  const client = new IaiClient(clientConfig);
  const params = {
    GroupIds:['20040808'],
    Image:imgbase,
    FaceMatchThreshold:50,//人脸相似度
    MaxFaceNum:1//最多返回4张人脸



  };
  client.SearchPersonsReturnsByGroup(params).then(
    (data) => {
      let aaa=data.ResultsReturnsByGroup[0].GroupCandidates[0].Candidates
      if(data.PersonNum==0){
        console.log("未找到完整人脸");
      }
      if(aaa.length==0){
        console.log("人脸不匹配");
      }else{
        console.log("匹配成功");
      }
    },
    (err) => {
      console.error("error", err);
      res.send({
        code:400,
        msg:"未成功"
      })
    }
  );
  
  
  
  
})
module.exports = router;